"""
应用初始化文件
负责创建和配置Flask应用实例
"""

from flask import Flask, send_from_directory
from flask_cors import CORS
import os
import sys

def create_app():
    """应用工厂函数"""
    app = Flask(__name__)

    # 配置CORS以允许跨域请求
    CORS(app)

    # 注册任务管理蓝图
    from app.tasks.routes import tasks_bp
    app.register_blueprint(tasks_bp, url_prefix='/api')

    # 注册日志流蓝图
    from app.logs_server.routes import logs_bp
    app.register_blueprint(logs_bp, url_prefix='/api')

    # 获取Vue静态文件路径的函数
    def get_resource_path(relative_path):
        """获取资源文件的绝对路径，兼容PyInstaller打包环境"""
        if hasattr(sys, '_MEIPASS'):
            # PyInstaller打包环境
            base_path = sys._MEIPASS
        else:
            # 开发环境
            base_path = os.path.abspath(os.path.dirname(__file__))
            base_path = os.path.join(base_path, '..')  # 回到项目根目录

        return os.path.join(base_path, relative_path)

    # 获取Vue静态文件目录
    static_files_path = get_resource_path(os.path.join('ui', 'dist'))

    # 只有当静态文件目录存在时才添加UI路由
    if os.path.exists(static_files_path) and os.path.isdir(static_files_path):
        @app.route('/ui/')
        def ui_index():
            return send_from_directory(static_files_path, 'index.html')

        @app.route('/ui/<path:path>')
        def ui_files(path):
            # 检查文件是否存在，如果不存在则返回index.html（支持Vue Router）
            if os.path.exists(os.path.join(static_files_path, path)):
                return send_from_directory(static_files_path, path)
            else:
                return send_from_directory(static_files_path, 'index.html')

    # 根路径
    @app.route('/')
    def home():
        ui_available = os.path.exists(static_files_path) if 'static_files_path' in locals() else False
        return {
            "message": "Python server is running",
            "ui_available": ui_available,
            "ui_access": "/ui/" if ui_available else "UI not available",
            "api_endpoints": {
                "task_management": {
                    "/api/tasks/start": "启动任务 (POST)",
                    "/api/tasks/status/<task_id>": "获取任务状态 (GET)",
                    "/api/tasks/reset/<task_id>": "重置任务 (DELETE)"
                },
                "log_stream": {
                    "/api/logs_server/stream": "SSE日志流端点 (GET)",
                    "/api/logs_server/start": "启动日志流生成 (POST)",
                    "/api/logs_server/stop": "停止日志流生成 (POST)",
                    "/api/logs_server/status": "获取日志流状态 (GET)"
                }
            }
        }

    return app
